#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Denis Kürov
# Licensed under the GNU General Public License, version 3.
# See the file http://www.gnu.org/copyleft/gpl.txt.


import os
from time import strftime
#custom modules
from iptables.models import Loadindex,Logs,Prefixer

class FireUtils(object):
    """ Some utilities for the firewall modules"""
    
    def generate_log_query(f_cat,f_word):
        """ The one gives back a queryset zip zip..."""
        
        sorgu=[]
        
        if f_cat=='p':
            #we need prefixes
            if f_word !='':
                res=Prefixer.objects.filter(pref_name__icontains=f_word)
                        
                if res:
                    ids=[x.id for x in res]
                    sorgu=Logs.objects.filter(parent_prefix__in=ids).order_by('parent_prefix','-log_date')
                            
                            
                            
                else:
                    sorgu=res
                    
            else:#if no search word was used
                sorgu=Logs.objects.order_by('parent_prefix','-log_date')
                
        ###################################################################################33
        elif f_cat=='sp':
            #search for source port        
            if f_word!='':
                sorgu=Logs.objects.filter(sport__icontains=f_word).order_by('sport','-log_date')
                        
            else:
                sorgu=Logs.objects.order_by('sport','-log_date')
                        
                ######################################################################################
                
        elif f_cat=='dp':
            if f_word!='':
                sorgu=Logs.objects.filter(dport__icontains=f_word).order_by('dport','-log_date')
                        
            else:
                sorgu=Logs.objects.order_by('dport','-log_date')
                        
        ################################################################333############3333###
                
        elif f_cat=='si':
            if f_word!='':
                sorgu=Logs.objects.filter(ip_src__icontains=f_word).order_by('ip_src','-log_date')
                        
            else:
                sorgu=Logs.objects.order_by('ip_src','-log_date')
                        
        #####################################################################################3####3
        elif f_cat=='di':
            if f_word!='':
                sorgu=Logs.objects.filter(ip_dst__icontains=f_word).order_by('ip_dst','-log_date')
                        
            else:
                sorgu=Logs.objects.order_by('ip_dst','-log_date')
                        
        ##########################################################################################
                
        elif f_cat=='sd':
            if f_word!='':
                sorgu=Logs.objects.filter(in_dev__icontains=f_word).order_by('in_dev','-log_date')
                        
            else:
                sorgu=Logs.objects.order_by('in_dev','-log_date')
        #########################################################################################33
                
        elif f_cat=='dd':
            if f_word!='':
                sorgu=Logs.objects.filter(outDev__icontains=f_word).order_by('outDev','-log_date')
                        
            else:
                sorgu=Logs.objects.order_by('outDev','-log_date')
                
        ######################################################################################
        
        return sorgu        
    
    generate_log_query=staticmethod(generate_log_query)
    
    def is_valid_port(port):
        
        port=int(port)
        
        if not port:
            return False
        
        if port<=65535 and port >=0:
            return True
        
        else:
            return False
        
    is_valid_port=staticmethod(is_valid_port)
    
    
    def active_device():
        """ Returns baack a tuple of actvive network cards"""
        
        dev=os.popen3("/sbin/ifconfig -s")
        dev=dev[1].read().split()
        
        final=[]
        final.append('any')
        
        counter=0
        
        for i in dev[12:]:
            if counter%12==0:
                final.append(i)
            
            counter=counter+1
                
        k=[(i,i) for i in final]
        
        return tuple(k)
        

    active_device=staticmethod(active_device)

    def get_loaded_rules():
        """ Gets the loaded ones"""
        final=[('last','son')]
        
        l=Loadindex.objects.order_by('ordering')
        
        if l:
            loaded=[(str(i.ordering),i.parent_rule.name) for i in l]
            final.extend(loaded)
            #final=tuple(final)
         
        return tuple(final)
    
    get_loaded_rules=staticmethod(get_loaded_rules)
    
    def control_flags(c_list,set_list):
        """ That one is controlling if the tcp flags are ok."""
        #print "Ben clist :",c_list
        #print "Ben set_list :",set_list
        
        if not c_list and not set_list:
            print "ikiside yok tamamdir" 
            return True
        
        if not c_list or not set_list:
            print "Biri yoksa digeri de olmamali"
            return False
        
        
        if len(c_list)==1 and c_list[0]=='ALL':
            print "All varsa tamam"
            return True
        
        else:
            if len(set_list)==1 and set_list[0]=='NONE':
                print "None varsa ok dir"
                return True
            
            for i in set_list:
                flag=False
                for j in c_list:
                    if j==i:
                        flag=True
                        break
                    
                if not flag:
                    print "Sol sagi kapsamalidir"
                    return False
        
        return True
    control_flags=staticmethod(control_flags)     

class AktiviteKaydet(object):
    """ That class is the logger of that application. Because it is very hard to know
    when a signal is called so it is better to log them"""
    
    def __init__(self,eylem=None):
        
        self.__eylem=eylem
        self.__dosya=None
        self.__durum=""
        self.__kural=""
        self.__extra={}
        
    def dosya_ac(self):
        """ opens the file to log activities"""
        fname="eylemci.txt"
        
        try:
            self.__dosya=open(fname,'a')
        
        except IOException,e:
            print "Dosya acarken hata var :",e
            return False
        
        return True
    
    def dosya_kapa(self):
        """ Closing the file"""
        try: 
            self.__dosya.close()
            
        except IOException,e:
            print "Dosya kapatirkene hata var ",e
            return False
            
        return True
    
    def set_durum(self,d):
        """ The result of the operation"""
        self.__durum=d
        
    def set_kural(self,k):
        """ If an iptables rule is created the details about it"""
        self.__kural=k
        
    def set_extra(self,**e):
        """ The extra log arguments if some exists"""
        self.__extra=e
        
    def set_eylem(self,e):
        """ Sets the eylem variable"""
        self.__eylem=e
        
    def reset_fields(self):
        """ A emergency or reusability method"""
        self.__eylem=""
        self.__durum=""
        self.__kural=""
        self.__extra=""
        
        if not self.__dosya:
            self.dosya_ac()
            
    def log_activity(self):
        """ The main part that logs"""
        splitter="#"*50
        c_time=strftime("%Y-%m-%d %H:%M:%S")
        
        final_log="".join([splitter,"\n","Zaman :",c_time,"\n","Eylem : ",self.__eylem,"\n","Kural :",self.__kural,"\n","Sonuc :",self.__durum,"\n","Extra : \n","".join(["%s : %s \n"%(key,value) for key,value in self.__extra.items()]),"\n",splitter])

        if self.__dosya:
            try:
                self.__dosya.write(final_log)
                
            except IOExcept,e:
                print "Hata cikti burada dosya yazarkene"
                return False
        
        else :
            return False
        
        
        self.reset_fields()
        return True
    
    
    
                

if __name__=="__main__":
    #print FireUtils.is_valid_port("12")
    FireUtils.active_device()